package cc.yiueil.config;

import cc.yiueil.filter.GuestFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.access.intercept.AuthorizationFilter;

import static org.springframework.security.config.Customizer.withDefaults;

@EnableMethodSecurity
@Configuration
public class SpringSecurityConfig {
    @Autowired
    GuestFilter guestFilter;

    @Bean
    SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        return http
                // 禁用默认的匿名账号
                .anonymous(AbstractHttpConfigurer::disable)
                // 手动添加一个游客filter到最后认证之前
                .addFilterBefore(guestFilter, AuthorizationFilter.class)
                .authorizeHttpRequests((requests) ->
                        requests.anyRequest().authenticated()
                )
                .csrf(AbstractHttpConfigurer::disable)
                .formLogin(withDefaults())
                .httpBasic(withDefaults()).build();
    }
}
